import axios from "axios";
import store from "@/store";
import router from "@/router";

import { Toast } from "vant";

// 创建axios实例
const conf = {
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 90000, // 请求超时时间
  withCredentials: true
};

const service = axios.create(conf);

// request拦截器
service.interceptors.request.use(
  config => {
    let userInfo = localStorage.getItem('userInfo');
    userInfo = JSON.parse(userInfo)
    if (userInfo && userInfo.token) {
      config.headers['AppToken'] = userInfo.token; // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config;
  },
  error => {
    console.log(error);
    Promise.reject(error);
  }
);

// respone拦截器
service.interceptors.response.use(
  response => {
    const res = response.data;
    if (response.config.responseType === "blob" || response.config.responseType === "arraybuffer") {
      return response;
    } else {
      if (res) {
        // 校验token失效
        if (res.code == 401) {
          Toast(res.message)
          store.dispatch('handleLogout');
          router.replace('/login', ()=>{},()=>{});
        } else if(res.code == 500) {
          Toast(res.message)
        } else {
          return res;
        }
      } else {
        return Promise.reject(new Error("Error"));
      }
    }
  },
  error => {
    if (error.response && error.response.status) {
      Toast(error.message)
    } else {
      Toast(error.message)
    }
    console.log("err" + error);
    return Promise.reject(error);
  }
);

export default service;
export { conf };
